<!DOCTYPE html>
<html>
<head>
	<style type="text/css">
	*{margin: 0;padding: 0}

	</style>
</head>

<body>
	<!-- <img id="img" src="http://img3.imgtn.bdimg.com/it/u=1577957864,2967915305&fm=26&gp=0.jpg"> -->
	<canvas id="cans1" width="800" height="400" style="background: #1c6995"></canvas>

  <script>
		window.onload=function(){
			let cans=document.getElementById('cans1');
			let cs=cans.getContext('2d');
			// let oimg=document.getElementById('img');
			let oimg=document.createElement('img');//两种写法效果一样
			// let oimg=new Image();
			oimg.src='kulou.jpg';
			let dir='l';
			document.onkeydown=function(ev){
				let keys={37:'l',38:'u',39:'r',40:'d'};//判断按键
				dir=keys[ev.keyCode]||dir;//判断按键
			}
			let x=200,y=200;//初始位置
			oimg.onload=function(){
				let time=0;
				setInterval(function(){
					cs.clearRect(0,0,cans.width,cans.height)

					let rows={'d':0,'r':1,'l':2,'u':3};	//方向

					cs.drawImage(oimg,45+36*time+time*72,32+rows[dir]*107,70,107,x,y,70,107)
					let speed=15;//速度
				switch(dir){
					
					case 'l':x-=speed;
						 if(x<=0){
							x=0;
						}
					break;
					case 'd':y+=speed;
						if(y>=cans.height){
							y=300;
						}
					break;
					case 'u':y-=speed;
						if(y<=0){
							y=0;
						}
					break;
					case 'r':x+=speed;
						if(x>=cans.width){
							x=710;
						}
					break;

				}


				time+=1;
				if(time==3){
					time=0;
				}
				},100)
			}
		}
			
  </script>
</body>
</html>
